<?php

namespace App\Services;

use App\Models\AfterSalesRequest;
use App\Models\AfterSalesItem;
use App\Models\AfterSalesApproval;
use App\Models\AfterSalesLogistic;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\LogisticsCompany;
use App\Models\SystemSetting;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AfterSalesService
{
    /**
     * 创建售后申请
     */
    public function createAfterSalesRequest(array $data, int $userId): AfterSalesRequest
    {
        return DB::transaction(function () use ($data, $userId) {
            $order = Order::findOrFail($data['order_id']);
            
            // 验证订单是否属于用户
            if ($order->user_id !== $userId) {
                throw new \Exception('无权操作此订单');
            }

            // 验证订单是否可以申请售后
            if (!$this->canApplyAfterSales($order)) {
                throw new \Exception('该订单无法申请售后');
            }

            // 创建售后申请
            $afterSalesRequest = AfterSalesRequest::create([
                'user_id' => $userId,
                'order_id' => $order->id,
                'type' => $data['type'],
                'reason' => $data['reason'],
                'description' => $data['description'] ?? null,
                'images' => $data['images'] ?? null,
                'status' => 'pending',
            ]);

            // 创建售后商品项并计算总金额
            $totalRequestedAmount = 0;
            $orderItemTotal = 0; // 订单项原价总和
            
            foreach ($data['items'] as $itemData) {
                $orderItem = OrderItem::findOrFail($itemData['order_item_id']);
                
                // 验证订单项是否属于指定订单
                if ($orderItem->order_id !== $order->id) {
                    throw new \Exception('所选商品不属于指定订单');
                }

                // 计算订单项原价
                $itemOriginalPrice = $orderItem->price * $itemData['quantity'];
                $orderItemTotal += $itemOriginalPrice;
                
                $calculationNote = $this->generateCalculationNote(
                    $orderItem->price,
                    $itemData['quantity'],
                    $itemOriginalPrice
                );

                AfterSalesItem::create([
                    'request_id' => $afterSalesRequest->id,
                    'order_item_id' => $orderItem->id,
                    'quantity' => $itemData['quantity'],
                    'refund_amount' => $itemOriginalPrice, // 先按原价记录
                    'calculation_note' => $calculationNote,
                ]);
            }

            // 计算实际退款金额（按用户实际支付比例）
            $orderActualPaid = $order->total_amount; // 用户实际支付金额
            $orderOriginalTotal = $order->subtotal_amount; // 订单原价总额
            $refundRatio = $orderItemTotal / $orderOriginalTotal; // 申请商品占原价比例
            $actualRefundAmount = $orderActualPaid * $refundRatio; // 按实际支付比例退款

            // 更新售后申请的总金额为实际退款金额
            $afterSalesRequest->update([
                'requested_amount' => $actualRefundAmount,
            ]);

            // 更新售后商品项的退款金额
            foreach ($afterSalesRequest->items as $item) {
                $itemRatio = $item->refund_amount / $orderItemTotal;
                $itemActualRefund = $actualRefundAmount * $itemRatio;
                $item->update(['refund_amount' => $itemActualRefund]);
            }

            Log::info('After-sales request created', [
                'request_id' => $afterSalesRequest->id,
                'user_id' => $userId,
                'order_id' => $order->id,
                'type' => $data['type'],
            ]);

            return $afterSalesRequest;
        });
    }

    /**
     * 审核售后申请
     */
    public function approveAfterSalesRequest(AfterSalesRequest $afterSalesRequest, int $adminId, string $reason = null): void
    {
        DB::transaction(function () use ($afterSalesRequest, $adminId, $reason) {
            $afterSalesRequest->update(['status' => 'approved']);
            
            // 记录审核信息
            AfterSalesApproval::create([
                'request_id' => $afterSalesRequest->id,
                'admin_id' => $adminId,
                'action' => 'approved',
                'reason' => $reason,
            ]);

            Log::info('After-sales request approved', [
                'request_id' => $afterSalesRequest->id,
                'admin_id' => $adminId,
            ]);
        });
    }

    /**
     * 拒绝售后申请
     */
    public function rejectAfterSalesRequest(AfterSalesRequest $afterSalesRequest, int $adminId, string $reason): void
    {
        DB::transaction(function () use ($afterSalesRequest, $adminId, $reason) {
            $afterSalesRequest->update(['status' => 'rejected']);
            
            // 记录审核信息
            AfterSalesApproval::create([
                'request_id' => $afterSalesRequest->id,
                'admin_id' => $adminId,
                'action' => 'rejected',
                'reason' => $reason,
            ]);

            Log::info('After-sales request rejected', [
                'request_id' => $afterSalesRequest->id,
                'admin_id' => $adminId,
                'reason' => $reason,
            ]);
        });
    }

    /**
     * 提交物流信息
     */
    public function submitLogistics(AfterSalesRequest $afterSalesRequest, array $data, string $submittedBy): AfterSalesLogistic
    {
        return DB::transaction(function () use ($afterSalesRequest, $data, $submittedBy) {
            // 验证是否已有相同类型的物流信息
            $existingLogistics = $afterSalesRequest->logistics()
                ->where('submitted_by', $submittedBy)
                ->first();

            if ($existingLogistics) {
                throw new \Exception('该售后申请已提交过物流信息');
            }

            // 创建物流信息
            $logistics = AfterSalesLogistic::create([
                'request_id' => $afterSalesRequest->id,
                'company' => $data['company'],
                'tracking_number' => $data['tracking_number'],
                'submitted_by' => $submittedBy,
                'status' => 'pending',
            ]);

            Log::info('Logistics submitted', [
                'request_id' => $afterSalesRequest->id,
                'submitted_by' => $submittedBy,
                'company' => $data['company'],
                'tracking_number' => $data['tracking_number'],
            ]);

            // 如果是换货申请且用户提交物流，自动更新换货状态
            if ($afterSalesRequest->type === AfterSalesRequest::TYPE_EXCHANGE && $submittedBy === 'user') {
                $afterSalesRequest->updateExchangeStatusFromLogistics();
            }

            return $logistics;
        });
    }

    /**
     * 完成售后申请
     */
    public function completeAfterSalesRequest(AfterSalesRequest $afterSalesRequest, int $adminId, string $reason = null): void
    {
        DB::transaction(function () use ($afterSalesRequest, $adminId, $reason) {
            $afterSalesRequest->update(['status' => 'completed']);
            
            // 记录完成信息
            AfterSalesApproval::create([
                'request_id' => $afterSalesRequest->id,
                'admin_id' => $adminId,
                'action' => 'completed',
                'reason' => $reason,
            ]);

            Log::info('After-sales request completed', [
                'request_id' => $afterSalesRequest->id,
                'admin_id' => $adminId,
            ]);
        });
    }

    /**
     * 取消售后申请
     */
    public function cancelAfterSalesRequest(AfterSalesRequest $afterSalesRequest): void
    {
        if (!$afterSalesRequest->canCancel()) {
            throw new \Exception('该售后申请无法取消');
        }

        $afterSalesRequest->markAsCancelled();

        Log::info('After-sales request cancelled', [
            'request_id' => $afterSalesRequest->id,
            'user_id' => $afterSalesRequest->user_id,
        ]);
    }

    /**
     * 获取售后申请列表
     */
    public function getAfterSalesRequestsForUser(int $userId, array $filters = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $query = AfterSalesRequest::where('user_id', $userId)
            ->with([
                'order.items.product.images',
                'order.items.variant.images',
                'items.orderItem.product',
                'items.orderItem.variant',
                'approvals.admin',
                'logistics',
            ]);

        // 状态筛选
        if (!empty($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        // 类型筛选
        if (!empty($filters['type'])) {
            $query->where('type', $filters['type']);
        }

        // 关键词搜索
        if (!empty($filters['keyword'])) {
            $keyword = $filters['keyword'];
            $query->where(function ($q) use ($keyword) {
                $q->where('reason', 'like', "%{$keyword}%")
                  ->orWhereHas('order', function ($orderQuery) use ($keyword) {
                      $orderQuery->where('order_number', 'like', "%{$keyword}%");
                  });
            });
        }

        return $query->orderBy('created_at', 'desc')->paginate(10)->withQueryString();
    }

    /**
     * 获取售后申请详情
     */
    public function getAfterSalesRequestDetails(int $requestId): AfterSalesRequest
    {
        return AfterSalesRequest::with([
            'order.items.product.images',
            'order.items.variant.images',
            'items.orderItem.product',
            'items.orderItem.variant',
            'approvals.admin',
            'logistics',
        ])->findOrFail($requestId);
    }

    /**
     * 验证订单是否可以申请售后（公开方法，供控制器调用）
     */
    public function validateOrderForAfterSales(Order $order): void
    {
        if (!$this->canApplyAfterSales($order)) {
            // 检查是否已有售后申请
            $existingRequest = AfterSalesRequest::where('order_id', $order->id)
                ->whereIn('status', ['pending', 'approved', 'processing'])
                ->first();
            
            if ($existingRequest) {
                throw new \Exception('该订单已有进行中的售后申请，请查看售后申请详情');
            } else {
                throw new \Exception('该订单暂不支持售后申请');
            }
        }
    }

    /**
     * 检查订单是否可以申请售后（内部方法）
     */
    private function canApplyAfterSales(Order $order): bool
    {
        // 订单必须是已送达状态
        if ($order->status !== 'delivered') {
            return false;
        }

        // 订单必须是已支付状态
        if ($order->payment_status !== 'paid') {
            return false;
        }

        // 从系统设置读取售后期限
        $refundPeriodDays = (int) SystemSetting::get('refund_period_days', 7);
        
        // 检查是否在售后期限内
        if (!$order->delivered_at) {
            return false;
        }
        
        $afterSalesDeadline = $order->delivered_at->addDays($refundPeriodDays);
        if (now()->gt($afterSalesDeadline)) {
            return false;
        }

        // 检查是否已有售后申请
        $existingRequest = AfterSalesRequest::where('order_id', $order->id)
            ->whereIn('status', ['pending', 'approved', 'processing'])
            ->first();
        
        if ($existingRequest) {
            return false;
        }

        return true;
    }

    /**
     * 生成退款计算说明
     */
    private function generateCalculationNote(float $price, int $quantity, float $refundAmount): string
    {
        return "按原价退款，单价：¥{$price}，数量：{$quantity}，计算：¥{$price} × {$quantity} = ¥{$refundAmount}";
    }

    /**
     * 获取物流公司列表
     */
    public function getLogisticsCompanies(): \Illuminate\Database\Eloquent\Collection
    {
        return LogisticsCompany::active()->ordered()->get(['id', 'name', 'code']);
    }
}
